package com.gitee.feizns.itrip.personal.utils.component.handler.exception;

import com.gitee.feizns.itrip.personal.beans.dto.Dto;
import com.gitee.feizns.itrip.personal.utils.service.exception.ServiceException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import static com.gitee.feizns.itrip.personal.utils.service.exception.ServiceException.VALIDATE_ERROR;

/**
 * @author feizns
 * @since 2019/1/14 0014
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数类型不匹配
     */
    private static final String METHOD_ARGUMENT_TYPE_MISMATCH = "000010";

    @ExceptionHandler({BindException.class})
    public Dto<String> validateHandler(BindException e) {
        return Dto.getFailDto(VALIDATE_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Dto<?> method(MethodArgumentNotValidException e) {
        return Dto.getFailDto(VALIDATE_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public Dto<String> serviceHandler(ServiceException e) {
        return Dto.getFailDto(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Dto<String> methodArgumentTypeMismatchHandler(MethodArgumentTypeMismatchException e) {
        return Dto.getFailDto(METHOD_ARGUMENT_TYPE_MISMATCH, "参数类型不匹配");
    }

    @ExceptionHandler(Throwable.class)
    public Dto<String> throwableHandler(Throwable e) {
        return Dto.getFailDto(ServiceException.UNKNOWN_ERROR, "未知的错误.");
    }

}